package com.yhy.common.utils;

import com.yhy.common.context.ThreadContextHelper;
import com.yhy.common.exception.CustomRuntimeException;
import com.yhy.common.token.JwtHelper;
import com.yhy.common.vo.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class YhyUtils {

    public static boolean isNumeric(String str) {
        return NumberUtils.isNumber(str);
        /*try {
            new BigDecimal(str);
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }
        return true;*/
    }

    public static Date truncateDateOfMinute(Date busDate) {
        Calendar calendar = DateUtils.toCalendar(busDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 日期时间格式化
     * @return
     */
    public static String genSysCode(String busModule) {
        String prefixName = StringUtils.isBlank(busModule) ? "" : BusCenterHelper.getBusCodePrefixByBusModule(busModule);
        return prefixName + genRandomYYMM();
    }

    public static String genId(String busModule) {
        if(StringUtils.isNotBlank(busModule) && BusCenterHelper.isNeedBarcode(busModule)) {
            return genBarcodeRandom();
        }
        String prefixName = StringUtils.isBlank(busModule) ? "" : BusCenterHelper.getIdPrefixByBusModule(busModule);
        return prefixName + genRandom();
    }

    public static String genRandomYYMM() {
        DateFormat format2 = new SimpleDateFormat("yyMMddHHmmssSSS");
        String curDateStr = format2.format(new Date());
        int end = new Random().nextInt(99);
        return curDateStr + String.format("%02d", end);
    }

    public static String genBarcodeRandom() {
        String curDateStr = "" + Calendar.getInstance().getTimeInMillis();
        return curDateStr;
    }

    public static String genRandom() {
        String curDateStr = "" + Calendar.getInstance().getTimeInMillis();
        int end = new Random().nextInt(99);
        return curDateStr + String.format("%02d", end);
    }

    public static String formatDate(Date time,String datePattern) {
        DateFormat format2 = new SimpleDateFormat(datePattern);
        return format2.format(time);
    }


    public static Date getCurDateTime() {
        return new Date();
    }

    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    public static String toMd5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'd', 'f'};
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static HttpServletRequest getRequest() {
        if(RequestContextHolder.getRequestAttributes() == null) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 根据资源路径获取资源的输入流
     * @param resourceLocation
     * @return
     */
    public static InputStream getInputStream(String resourceLocation) {
        if (resourceLocation.startsWith(org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX)) {
            String path = resourceLocation.substring(org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX.length());
            ClassLoader cl = ClassUtils.getDefaultClassLoader();
            return cl.getResourceAsStream(path);
        }
        try {
            return new FileInputStream(org.springframework.util.ResourceUtils.getFile(resourceLocation));
        } catch (FileNotFoundException e) {
            throw new CustomRuntimeException("FileNotFoundException", e);
        }
    }

    public static SysUser getSysUser() {
        SysUser sysUser = ThreadContextHelper.getParameter(JwtHelper.SYS_USER);
        return sysUser;
        /*HttpServletRequest request = getRequest();
        if(request == null) {
            return null;
        }
        Object sysUser = request.getAttribute(JwtHelper.SYS_USER);
        if(sysUser == null) {
            return null;
        }
        return (SysUser) sysUser;*/
    }

    public static void testDecrypt(String encryptedText) {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();

        // 解密的算法，需同加密算法相同
        config.setAlgorithm("PBEWithMD5AndDES");
        //解密的密钥，需同加密密钥相同
        config.setPassword("hyyang");
        standardPBEStringEncryptor.setConfig(config);
        String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
        System.out.println(plainText);
    }

    public static void main(String... args) {
        //testDecrypt("CrhN35iZ6ofZzxtATDrG8w==");

        System.out.println(genRandom());
        System.out.println(genRandom());
        System.out.println(genRandom());
        /*
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();

        // 加密的算法，这个算法是默认的
        config.setAlgorithm("PBEWithMD5AndDES");
        //加密的密钥，自定义
        config.setPassword("hyyang");
        standardPBEStringEncryptor.setConfig(config);
        String encryptedText = standardPBEStringEncryptor.encrypt("sgm#2019");
        System.out.println(encryptedText);*/
    }


}
